Imports System.IO
Imports MiscUtil.Conversion

Namespace IO
    Public Class EndianBinaryReader
        Inherits BinaryReader

        Private m_MiscUtil As MiscUtil.Conversion.BigEndianBitConverter

        Public Sub New(ByVal Input As Stream)
            MyBase.New(Input)
            m_MiscUtil = New BigEndianBitConverter
        End Sub

        Public Sub New(ByVal Input As Stream, ByVal Encoding As System.Text.Encoding)
            MyBase.New(Input, Encoding)
            m_MiscUtil = New BigEndianBitConverter
        End Sub

        Public Function ReadInt32Endian(ByVal Position As Long) As Int32
            Dim FileStream As FileStream
            Dim Buffer As Byte() = New Byte(4) {}

            FileStream = Convert.ChangeType(Me.BaseStream, GetType(FileStream))

            FileStream.Seek(Position, SeekOrigin.Begin)
            FileStream.Read(Buffer, 0, 4)

            Return m_MiscUtil.ToInt32(Buffer, 0)
        End Function

        Public Function ReadInt16Endian(ByVal Position As Long) As Int16
            Dim FileStream As FileStream = Nothing
            Dim Buffer As Byte() = New Byte(2) {}

            Me.BaseStream.CopyTo(FileStream)
            FileStream.Seek(Position, SeekOrigin.Begin)
            FileStream.Read(Buffer, 0, 2)

            Return m_MiscUtil.ToInt16(Buffer, 0)
        End Function

        Public Function ReadInt16Endian() As Int16
            Return ReadInt16Endian(Me.BaseStream.Position)
        End Function
    End Class
End Namespace